﻿#region Using Statements
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.Collections.Generic;
using System;
using Microsoft.Xna.Framework.Input;
#endregion

namespace pigs
{
    /// <summary>
    /// The options screen is brought up over the top of the main menu
    /// screen, and gives the user a chance to configure the game
    /// in various hopefully useful ways.
    /// </summary>
    class GameOverScreen : MenuScreen
    {
        List<Player> players;

        ContentManager content;
        SpriteFont font;
        GameSettings settings;

        int totalDeaths;
        int score;
        
        Boolean highScore;
        KeyboardState keyboard;
        KeyboardState preKey;

        MenuEntry saveNameMenuEntry;
        MenuEntry MainMenuEntry;

        String levelName;

        /// <summary>
        /// Constructor.
        /// </summary>
        public GameOverScreen(List<Player> player, GameSettings set, String level)
            : base("Game Over")
        {
            this.levelName = level;
            this.settings = set;
            players = player;
            init();
        }

        void init()
        {
            doHighScoresInfo();

            keyboard = Keyboard.GetState();
            preKey = Keyboard.GetState();

            // Add entries to the menu.
            MainMenuEntry = new MenuEntry("Main Menu");
            MainMenuEntry.Selected += MainMenuEntrySelected;

            if (highScore)
            {
                MenuEntry blankMenuEntry = new MenuEntry("");
                blankMenuEntry.isSelectable = false;
                MenuEntries.Add(blankMenuEntry);
                saveNameMenuEntry = new MenuEntry("Save");
                saveNameMenuEntry.Selected += saveNameMenuEntrySelected;
                MenuEntries.Add(saveNameMenuEntry);
                this.selectedEntry++;
            }

            MenuEntries.Add(MainMenuEntry);

            GamePad.SetVibration(PlayerIndex.One, 0f, 0f);
            GamePad.SetVibration(PlayerIndex.Two, 0f, 0f);
            GamePad.SetVibration(PlayerIndex.Three, 0f, 0f);
            GamePad.SetVibration(PlayerIndex.Four, 0f, 0f);
        }
        
        void doHighScoresInfo()
        {
            this.input = "";
            score = 0;
            foreach (Player p in players)
            {
                score += p.score;
            }
            highScore = settings.hs.newHighScore(levelName, score);

            this.totalDeaths = 0;
            foreach (Player p in players) this.totalDeaths += p.deathCouth;
        }

        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                LoadingScreen.Load(ScreenManager, false, null, new BackgroundScreen(), new Menu(settings));
            }

            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            if (highScore)
            {
                preKey = keyboard;
                keyboard = Keyboard.GetState();

                if (preKey != keyboard)
                {
                    getInput(keyboard);
                }
                if (input.Length > 12)
                    input = input.Substring(0, input.Length - 1);
            }
        }
        
        void saveNameMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            MenuEntries.Clear();

            // Add entries to the menu.
            MenuEntry MainMenuEntry = new MenuEntry("Main Menu");
            MainMenuEntry.Selected += MainMenuEntrySelected;
            MenuEntries.Add(MainMenuEntry);

            highScore = false;
            selectedEntry = 0;
            settings.hs.updateScores(levelName, input, score);
        }
        
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");

            this.font = content.Load<SpriteFont>("fonts/menufont");
        }

        /// <summary>
        /// Event handler for when the Quit Game menu entry is selected.
        /// </summary>
        void MainMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            LoadingScreen.Load(ScreenManager, false, null, new BackgroundScreen(), new Menu(settings));
        }

        /// <summary>
        /// Draws the loading screen.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
            Vector2 viewportSize = new Vector2(viewport.Width, viewport.Height);

            base.Draw(gameTime);

            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

            // Darken down any other screens that were drawn beneath the popup.
            ScreenManager.FadeBackBufferToBlack(TransitionAlpha / 3);

            // Draw the text.
            spriteBatch.Begin();

            if (highScore)
            {
                Vector2 pos = font.MeasureString("You have a High Score, What is your name?");
                spriteBatch.DrawString(font, "You have a High Score, What is your name?", new Vector2((viewport.Width - pos.X) / 2, 100), Color.White);
                pos = font.MeasureString(input);
                spriteBatch.DrawString(font, input, new Vector2((viewport.Width - pos.X)/2, 150), Color.White);
            }

            spriteBatch.DrawString(font, "Player ", new Vector2(viewport.Width / 5 - 50, (viewport.Height / 3) + 50), Color.White);
            spriteBatch.DrawString(font, "Score", new Vector2(2* viewport.Width / 5 - 50, (viewport.Height / 3) + 50), Color.White);
            spriteBatch.DrawString(font, "Accuracy", new Vector2(3 * viewport.Width / 5 - 50, (viewport.Height / 3) + 50), Color.White);
            spriteBatch.DrawString(font, "Deaths", new Vector2(4 * viewport.Width / 5 - 50, (viewport.Height / 3) + 50), Color.White);

            for (int i = 0; i < players.Count; i++)
            {
                drawStats(i, spriteBatch, viewport);
            }

            if (players.Count > 1)
            {
                int score = 0;
                int shots = 0;
                int hits = 0;
                foreach (Player p in players)
                {
                    score += p.score;
                    shots += p.shotsFired;
                    hits += p.pigsHit;
                }
                int acc = 0;
                if (shots > 0)
                {
                    acc = hits * 100 / shots;
                }
                spriteBatch.DrawString(font, "Total", new Vector2(viewport.Width / 5 - 50, (viewport.Height / 3) + (players.Count + 2) * 50), Color.White);
                spriteBatch.DrawString(font, score.ToString(), new Vector2(2 * viewport.Width / 5 - 50, (viewport.Height / 3) + (players.Count + 2) * 50), Color.White);
                spriteBatch.DrawString(font, acc.ToString(), new Vector2(3 * viewport.Width / 5 - 50, (viewport.Height / 3) + (players.Count + 2) * 50), Color.White);
                spriteBatch.DrawString(font, totalDeaths.ToString(), new Vector2(4 * viewport.Width / 5 - 50, (viewport.Height / 3) + (players.Count + 2) * 50), Color.White);
            }
            spriteBatch.End();
        }

        void drawStats(int i, SpriteBatch spriteBatch, Viewport viewport)
        {
            spriteBatch.DrawString(font, "Player " + (i + 1), new Vector2(viewport.Width / 5 - 50, (viewport.Height / 3) + (i + 2) * 50), Color.White);
            spriteBatch.DrawString(font, players[i].score.ToString(), new Vector2(2 * viewport.Width / 5 - 50, (viewport.Height / 3) + (i + 2) * 50), Color.White);
            if (players[i].shotsFired > 0)
            {
                spriteBatch.DrawString(font, players[i].accuracy.ToString() + "%", new Vector2(3 * viewport.Width / 5 - 50, (viewport.Height / 3) + (i + 2) * 50), Color.White);
            }
            else
            {
                spriteBatch.DrawString(font, "---%", new Vector2(3 * viewport.Width / 5 - 50, (viewport.Height / 3) + (i + 2) * 50), Color.White);
            }
            spriteBatch.DrawString(font, players[i].deathCouth.ToString(), new Vector2(4 * viewport.Width / 5 - 50, (viewport.Height / 3) + (i + 2) * 50), Color.White);
        }
    }
}
